package com.iqilu.ksd.activity;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.event.ChangeUserInfoEvent;
import com.iqilu.ksd.utils.BaseUtils;
import com.iqilu.ksd.utils.EncryptUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.jude.swipbackhelper.SwipeBackHelper;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

/**
 * Created by Coofee on 2016/9/20.
 */
public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SwipeBackHelper.onCreate(this);
        SwipeBackHelper.getCurrentPage(this)
                .setSwipeBackEnable(true)
                .setSwipeSensitivity(0.5f)
                .setSwipeRelateEnable(true)
                .setSwipeRelateOffset(300);
    }

    // 用户hash登录
    public void hashLogin() {
        String loginHash = SPUtils.getPref(this, UserInfo.LOGINHASH, "");
        String mPushKey = JPushInterface.getRegistrationID(this);
        String url = Api.URL_USER_HASHLOGIN + "?loginhash=" + loginHash + "&pushkey=" + mPushKey;
        final MyApplication application = (MyApplication) getApplication();
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
//                application.setUser(null);
//                EventBus.getDefault().post(new ChangeUserInfoEvent());
            }

            @Override
            public void onResponse(String response, int id) {
                UserBean user = null;
                JSONObject jsonObject = null;
                int status = 0;
                try {
                    jsonObject = new JSONObject(response);
                    status = jsonObject.getInt("status");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (status == 1) {
                    user = JSONUtils.requestDetail(response, "data", UserBean.class);
                }
                if (user != null && user.getId() > 0) {
                    application.setUser(user);
                    SPUtils.setPref(getApplicationContext(), UserInfo.LOGINHASH, user.getLoginhash());
                    EventBus.getDefault().post(new ChangeUserInfoEvent());
                }
            }
        });
    }

    // 登录加密
    public String getEncryptStr(String url) {
        String query = "_platform=android";
        UserBean user = ((MyApplication) getApplication()).getUser();
        if (user != null && user.getId() > 0) {
            String timeStamp = "" + System.currentTimeMillis() / 1000;
            String signStr = EncryptUtils.md5("" + user.getId() + timeStamp + Config.LOGIN_ENCRYPT_KEY);
            String encryptStr = "" + user.getId() + "\n" + BaseUtils.getDeviceId(this) + "\n" + timeStamp + "\n" + signStr;
            String aesStr = BaseUtils.AESencrypt(encryptStr, Config.LOGIN_ENCRYPT_KEY, Config.LOGIN_AES_IV);
            query = "__id=" + Uri.encode(aesStr) + "&_platform=android";
        } else {
            query = "__id=&_platform=android";
        }
        if (url.contains("?")) {
            url = url + "&" + query;
        } else {
            url = url + "?" + query;
        }
        return url;
    }

    public void setZHTypeface(TextView tv) {
        Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/FZLTZHUNHK.TTF");
        tv.setTypeface(typeFace);
    }

    public <T extends View> T getView(int id) {
        return (T) findViewById(id);
    }

    public <T extends View> T getView(View view, int id) {
        return (T) view.findViewById(id);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
//        super.attachBaseContext(newBase);
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
        MobclickAgent.onResume(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        SwipeBackHelper.onPostCreate(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
        SwipeBackHelper.onDestroy(this);
    }
}
